package net.huashitong.zhApp.controller;

import com.sirdc.modules.utils.ObjectUtils;
import com.sirdc.modules.utils.StringUtils;
import net.huashitong.Project.util.MessageUtil;
import net.huashitong.oversee.entity.Coordinate;
import net.huashitong.oversee.entity.SupervisionTask;
import net.huashitong.oversee.filter.CoordinateFilter;
import net.huashitong.oversee.filter.SupervisionTaskFilter;
import net.huashitong.oversee.service.CoordinateService;
import net.huashitong.oversee.service.SupervisionTaskService;
import net.huashitong.user.entity.BnpUser;
import net.huashitong.utils.UtilsTools;
import net.huashitong.zhApp.service.AppQuestionReportService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/zhApp/questionReport")
public class AppQuestionReportController extends BaseCtrl {

    @Autowired
    private CoordinateService coordinateService;
    @Autowired
    private AppQuestionReportService appQuestionReportService;
    @Autowired
    private SupervisionTaskService taskService;
    @Autowired
    private MessageUtil mu;

    @ResponseBody
    @RequestMapping(value = "/lists", method = RequestMethod.POST)
    public Map<String, Object> queryLists(@RequestBody CoordinateFilter filter) {
        BnpUser user = queryUserAuth(filter.getUserPhone());
        if (ObjectUtils.isBlank(user)) {
            return coverMessage("202", "无用户权限");
        }
        filter.setUserinfo(user.getPhone());
        filter.setBranchType(user.getBranchType()); //Set query permission
        if (StringUtils.isBlank(filter.getGroupCode())) //督查组权限
        {
            filter.setGroupCode(user.getGroupCode());
        }
        List<Coordinate> lists = coordinateService.queryCoordinate(filter);
        Map<String, Object> result = new HashMap<>();
        result.put("code", "200");
        result.put("message", "成功获取数据");
        result.put("userAuth", user);
        result.put("data", lists);
        result.put("count", filter.getPaging().getRecords());
        return result;
    }


    /**
     * 创建提请协调(APP端)
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/createQuestion", method = RequestMethod.POST)
    public Map<String, Object> createQuestion(@RequestBody CoordinateFilter filter) {
        BnpUser user = queryUserAuth(filter.getUserPhone());
        if (ObjectUtils.isBlank(user)) {
            return coverMessage("202", "无用户权限");
        }
        boolean flag = appQuestionReportService.createQuestion(filter, user);

        Map<String, Object> result = new HashMap<>();
        if(flag){
            result.put("code", "200");
            result.put("message", "保存成功");
            result.put("userAuth", user);
        }else{
            result.put("code", "202");
            result.put("message", "保存失败");
            result.put("userAuth", user);
        }
        return result;
    }

    /**
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/updateQuestion", method = RequestMethod.POST)
    public Map<String, Object> updateQuestion(@RequestBody CoordinateFilter filter) {
        BnpUser user = queryUserAuth(filter.getUserPhone());
        if (ObjectUtils.isBlank(user)) {
            return coverMessage("202", "无用户权限");
        }
        boolean flag = appQuestionReportService.updateQuestion(filter);
        Map<String, Object> result = new HashMap<>();
        if(flag){
            result.put("code", "200");
            result.put("message", "更新成功");
            result.put("userAuth", user);
            return result;
        }else{
            result.put("code", "202");
            result.put("message", "更新失败");
            result.put("userAuth", user);
            return result;
        }

    }


    /**
     * 问题转批（生成攻坚）
       * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/turnTackTask", method = RequestMethod.POST)
    public Map<String, Object> turnTackTask(@RequestBody CoordinateFilter filter) throws ParseException {
        Map<String, Object> result = new HashMap<>();
        Coordinate coor = coordinateService.getById(filter.getSysId());
        if ("2".equals(coor.getAaa001())) {
            result.put("code", "200");
            result.put("message", "更新成功");
            return result;
        }
        List<SupervisionTask> list = new ArrayList<>();
        if (StringUtils.isNotBlank(coor.getNodeSysId())) {
            SupervisionTaskFilter taskFilter = new SupervisionTaskFilter();
            taskFilter.setNodeSysId(coor.getNodeSysId());
            list = taskService.querySupervisionTaskByFilter(taskFilter);
        }
        filter.setProjectName(coor.getProjectName());
        filter.setInvolveUnit(coor.getInvolveUnit());
        filter.setResDept(coor.getResDept());
        filter.setResUser(coor.getResUser());
        filter.setResUserPhone(coor.getResUserPhone());
        filter.setOperator(coor.getOperator());
        filter.setOperatorPhone(coor.getOperatorPhone());
        String startDate = UtilsTools.getCurrentDate();
        String endDate = UtilsTools.plusDay(10, startDate);
        filter.setStartDate(startDate);
        filter.setEndDate(endDate);
        filter.setResDept(coor.getResDept());
        //如果list不为空则表示对已生成的督查任务进行提请协调
        if(StringUtils.isNotBlank(coor.getTaskId())){
            SupervisionTask task = taskService.getById(coor.getTaskId());
            if(ObjectUtils.isNotBlank(task)){
                filter.setTaskId(coor.getTaskId());
                filter.setTaskName(task.getTaskName());
                filter.setTaskContent(task.getTaskContent());
            }
        }
        String sysid = taskService.saveAutoTaskJob(filter, list);
        // 转为攻坚督查
        coor.setAaa001("2");
        coordinateService.update(coor);
        //通知县分管领导
        if (StringUtils.isNotBlank(coor.getfGcountyLeaderPhone()) && StringUtils.isNotBlank(coor.getfGcountyLeader())) {
            mu.sendTackMessageToFGLeader(coor);
        }

        //保存到督查系统（APP）
        //taskService.saveTasktoDuCha(sysid);

        result.put("code", "200");
        result.put("message", "问题已转批生成攻坚");
        return result;
    }


    /**
     * 撤销协调
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/revoke", method = RequestMethod.POST)
    public Map<String, Object> addProblem(@RequestBody CoordinateFilter filter) {
        Map<String, Object> result = new HashMap<>();
        String sysId = filter.getSysId();
        Coordinate coordinate = coordinateService.getById(sysId);
        if (ObjectUtils.isNotBlank(coordinate)) {
            //撤销协调
            coordinate.setAaa001("0");
            coordinate.setRevokeReason(filter.getRevokeReason());   //撤销原因
            if (StringUtils.isNotBlank(coordinate.getNodeSysId())) {
                //验证是否已有相关问题，有的话则撤销督查任务任务中的攻坚任务标志
                SupervisionTaskFilter taskFilter = new SupervisionTaskFilter();
                taskFilter.setNodeSysId(coordinate.getNodeSysId());
                List<SupervisionTask> supervisionTasks = taskService.getTaskListsNoPage(taskFilter);

                if (ObjectUtils.isNotBlank(supervisionTasks) && supervisionTasks.size() > 0) {
                    for (SupervisionTask sup : supervisionTasks) {
                        sup.setTackFlag(null);
                    }
                    taskService.batchUpdate(supervisionTasks);
                }
            } else {
                result.put("code", "201");
                result.put("message", "内部出错");
                return result;
            }
        } else {
            result.put("code", "201");
            result.put("message", "内部出错");
            return result;
        }
        coordinateService.update(coordinate);
        result.put("code", "200");
        result.put("message", "请求成功");
        return result;
    }

}
